package com.smvc.handlers;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.smvc.entities.User;

@Controller
@RequestMapping("param")
public class ParamHandler {

	private final String OK = "ok";

	/**
	 * 使用@PathVariable传递参数，把参数放在路径里面
	 */
	@RequestMapping("pathVariable/{id}/{name}")
	public String pathVariable(@PathVariable("id") Integer id, @PathVariable("name") String name) {
		System.out.println("pathVariable:" + id + "," + name);
		return OK;
	}

	/**
	 * 使用@RequestParam传递参数， value ： 参数名 required ： 是否必须 defaultValue ： 默认值
	 */
	@RequestMapping("requstParam")
	public String requstParam(@RequestParam(value = "username") String name,
			@RequestParam(value = "age", required = false, defaultValue = "0") int age) {
		System.out.println("requstParam,username:" + name + ",age:" + age);
		return OK;
	}

	/**
	 * 使用POJO传递参数，支持级联属性
	 */
	@RequestMapping("pojo")
	public String pojo(User user) {
		System.out.println(user);
		return OK;
	}

	/**
	 * 使用原声Servlet API作为入参，使用request取值
	 */
	@RequestMapping("servlerAPI")
	public void servletAPI(HttpServletRequest request, HttpServletResponse response, Writer writer) throws IOException{
		String name = request.getParameter("name");
		System.out.println(name);
		writer.write("Hello,SpringMVC");
	}
	
	/**
	 * 放入Cookie
	 */
	@RequestMapping("testCookie")
	public String addCookie(HttpServletResponse response){
		response.addCookie(new Cookie("loginName", "liuxing"));
		return OK;
	}
	
	/**
	 * 取出已经放入的Cookie
	 */
	@RequestMapping("cookieValue")
	public String cookieValue(@CookieValue("loginName") String loginName){
		System.out.println(loginName);
		return OK;
	}
}
